package com.xl.flinkdemo.sink输出操作;

import com.xl.flinkdemo.entity.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.sink.SinkFunction;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;

public class SinkTest_Redis {
    public static void main(String[] args) throws Exception {
        // 创建执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);
        // 从文件中读取数据
        String inputPath = "D:\\myWork\\flinkdemo\\src\\main\\resources\\sensors";

        //得到数据源
        DataStream<String> inputdataStream = env.readTextFile(inputPath);
        DataStream<SensorReading> dataStream =
                inputdataStream.map(new MapFunction<String, SensorReading>() {
                    @Override
                    public SensorReading map(String s) throws Exception {
                        String[] fields = s.split(",");
                        return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2]));
                    }
                });

        //定义jedis连接配置
        FlinkJedisPoolConfig config =new  FlinkJedisPoolConfig.Builder()
                .setHost("192.168.78.133")
                .setPort(6379).setPassword("12345678").build();
        dataStream.addSink(new RedisSink<>(config, new RedisMapper<SensorReading>() {
            //定义保存数据到redis的命令，存成hash表，hset sensor_temp id temperature
            @Override
            public RedisCommandDescription getCommandDescription() {
                return new RedisCommandDescription(RedisCommand.HSET,"sensor_temp");
            }

            @Override
            public String getKeyFromData(SensorReading sensorReading) {
                return sensorReading.getId();
            }

            @Override
            public String getValueFromData(SensorReading sensorReading) {
                return sensorReading.getSensors().toString();
            }
        }));

        env.execute();
    }

}
